package com.gdth.bank.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.bean.DownloadBean;
import com.gdth.bank.bean.XtBbGxBean;
import com.gdth.bank.event.MessageEvent;
import com.gdth.bank.model.TAppTokenModel;
import com.gdth.bank.presenter.XtBbGxPresenter;
import com.gdth.bank.ui.MainFragment;
import com.gdth.bank.ui.NotificationFragment;
import com.gdth.bank.ui.UserFragment;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.utils.SharedPreferencesUtil;
import com.gdth.bank.utils.StatusBarUtil;
import com.gdth.bank.view.XtBbGxView;
import com.gdth.bank.widget.NotificationMenuWindow;
import com.gdth.bank.widget.NotificationMenuWindow.onNotificationMenuItemClickListener;
import com.gdth.bank.widget.SearchNotificationWindow;
import com.gdth.bank.widget.SearchNotificationWindow.onSearchListener;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseFragmentActivity;
import com.gdth.database.bean.TAppYh;
import com.gdth.database.bean.getNewMoney;
import com.gdth.http.callback.DownLoadCallback;
import com.gdth.http.listener.UIProgressListener;
import com.gdth.http.listener.impl.UIProgressListenerImpl;
import com.gdth.http.method.EngDNS;
import com.gdth.http.method.ProgressHelper;
import com.gdth.http.method.httpsUtils;
import com.gdth.resource.Constant;
import com.gdth.service.BaseAction;
import com.gdth.thread.DownLoadThread;
import com.gdth.utils.GsonUtil;
import com.gdth.utils.PermissionUtil;
import com.gdth.utils.ToolUtil;
import com.gdth.widget.dialog.DialogConfig;
import com.gdth.widget.dialog.DialogProgressBar;
import com.gdth.widget.viewpager.adapter.BasePagerAdapter;
import com.google.gson.Gson;
import com.tencent.bugly.crashreport.CrashReport;

import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class MainTabActivity extends BaseFragmentActivity implements XtBbGxView, OnClickListener,BottomNavigationView.OnNavigationItemSelectedListener {
	/**心跳包功能**/

//	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
//	@ViewInject(id=R.id.header_btn_left) TextView txt_header_left;
//    @ViewInject(id=R.id.header_btn_right) TextView txt_header_right;
////    @ViewInject(id=R.id.notification_number) TextView notification_number;
//    @ViewInject(id=R.id.header_btn_menu) TextView header_btn_menu;
	@ViewInject(id=R.id.mBottomNavigation)
	BottomNavigationView mBottomNavigation;

	@ViewInject(id=R.id.main_view_pager) ViewPager viewPager;
//	@ViewInject(id=R.id.main_linear_nav) LinearLayout linear_nav;
//@ViewInject(id=R.id.srearch_all) LinearLayout srearch_all;
	
//	@ViewInject(id=R.id.input_content) EditText input_content;
//	@ViewInject(id=R.id.spinner1) Spinner spinner;
//	@ViewInject(id=R.id.hide_view) ImageView hideView;
//	@ViewInject(id=R.id.sure_search) TextView sureSearch;
//	@ViewInject(id=R.id.sure_search_img) ImageView sure_search_img;
//	@ViewInject(id=R.id.go_back) TextView go_back;
	@ViewInject(id=R.id.go_back_img) ImageView go_back_img;

    /**
     * 同一个应用内的不同组件间发送Broadcast
     */
    private LocalBroadcastManager mLocalBroadcastManager;
    
    private HBroadcastReceiver mHBroadcastReceiver;
    private NotificationFragment mNotificationFragment;
    
	/** 主页 **/
	private MainFragment mMainFragment;
	/** 用户信息 **/
	private UserFragment mUserFragment;
	private ArrayList<View> viewList;
	private Drawable[] nDrawable, pDrawable;
	private String msg;
	XtBbGxPresenter  mXtBbGxPresenter;
	String mc,apkname,verName, path;
	int verCode;
	DialogConfig config;
	private List<TextView> textList;
	private DialogProgressBar mProgressBar;
	int[] sList;
	private static final OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(1000, TimeUnit.MINUTES)
    .readTimeout(1000, TimeUnit.MINUTES)
    .writeTimeout(1000, TimeUnit.MINUTES)
	.dns(new EngDNS())
    .sslSocketFactory(httpsUtils.getSSLSocketFactory())
	.hostnameVerifier(httpsUtils.getHostnameVerifier())
    .build();

	
    LinearLayout.LayoutParams ll_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);

	private int currIndex = 0;//当前页卡编号
	
	public TAppYh mUser;
	
	NotificationMenuWindow mPopupMenu;
	private static final String FInish_DEl = "完成";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_tab);
		EventBus.getDefault().register(this);
		initView();
		
		initService();

		BankApplication.getApp().isLogin = true;
		getTbxxbList();
		
		initGxBb();
		PermissionUtil.checkPermissionCamera(this);
		
		
	}
	
	private void getTbxxbList() {
		// TODO Auto-generated method stub
		SharedPreferences preferences = getSharedPreferences("param", MODE_PRIVATE);
		String moneyNumber = preferences.getString("moneyNumber", "0.00");// 获取本地存储数据
		String moneyTime = preferences.getString("moneyTime", "1970-1-1");// 获取本地存储数据
		boolean isShowMoney = SharedPreferencesUtil.getSharePreferencesByKeyForBoolean(MainTabActivity.this,"paramMoney","isShowMoney");
		mMainFragment.changeAllMoney(moneyNumber,moneyTime,isShowMoney);
		new DownLoadThread().startDownload();
	}
	 private int dp2px(Context context,float dpValue){
	        float scale=context.getResources().getDisplayMetrics().density;
	        return (int)(dpValue*scale+0.5f);
	    }
	

	/**
	 * 初始化标签名
	 */
	public void initView(){
		mUser = BankApplication.mInstance.getCurrentUser();
		if(null != mUser || null != mUser.getSfz() || !mUser.getSfz().equals("")) {
			CrashReport.setUserId(MainTabActivity.this,mUser.getSfz());	
		}
//		txt_header_left.setVisibility(View.GONE);
//		txt_header_right.setVisibility(View.GONE);
		//srearch_all.setVisibility(View.GONE);
//		txt_header_title.setText("主页");
		DisplayMetrics dm   = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
		mMainFragment = new MainFragment(this);
		mUserFragment = new UserFragment(this);
		viewList = new ArrayList<View>();
		viewList.add(mMainFragment);
		viewList.add(mUserFragment);
		
		//给ViewPager设置适配器
		viewPager.setAdapter(new BasePagerAdapter(viewList));
		if(Constant.isOpenNotification) {
			viewPager.setCurrentItem(1);//设置当前显示标签页为第一页
		}else {
			viewPager.setCurrentItem(0);//设置当前显示标签页为第一页
		}
		mBottomNavigation.setOnNavigationItemSelectedListener(this);
		viewPager.addOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器
    	mPopupMenu = new NotificationMenuWindow(this, 340, LayoutParams.WRAP_CONTENT);
	        mPopupMenu.setOnPopupMenuItemClickListener(new PopNotification());  


	}
	private int selType = 1;
	public void initService(){
		IntentFilter mIntentFilter = getIntentFilter();
//		获取实例
		mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mHBroadcastReceiver = new HBroadcastReceiver();
        mLocalBroadcastManager.registerReceiver(mHBroadcastReceiver, mIntentFilter);
	}
	
	public void initGxBb(){
		mProgressBar = new DialogProgressBar(this, getResources().getString(R.string.param243));
		mXtBbGxPresenter  = new XtBbGxPresenter(this);
		mXtBbGxPresenter.getBbGx("content");
	}
	private OnClickListener downloadClickListener = new  OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			config.dismiss();
			DownloadBean bean = new DownloadBean();
			bean.setName(apkname);
			bean.setScms(0);
			bean.setCjsj(new Date());
			bean.setPath(path);
			bean.setGnmk(5);
			bean.setLocalPath(ToolUtil.getFilePath(apkname));
			mProgressBar.show();
			mProgressBar.setCancelable(false);
			download(bean);
		}
	};
	
	@Override
	protected void onStart() {
		super.onStart();
	}
	 
	@Override
	protected void onStop() {
		super.onStop();
	}
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void Notification(MessageEvent messageEvent) {		//
		switch (messageEvent.getType()){
			case MessageEvent.NOTIFICATION_DEL:			
				mNotificationFragment.delNotification(messageEvent.getMessage());
				break;
			case MessageEvent.NOTIFICATION_NEWDATA:
				mNotificationFragment.onGetLocalData(false);
				break;
			case MessageEvent.NOTIFICATION_READ:
//				mNotificationFragment.onGetLocalData(false);
				mNotificationFragment.readNotification(messageEvent.getMessage());
				
				break;
			case MessageEvent.NOTIFICATION_GET:
				mNotificationFragment.onGetLocalData(false);				
				break;
			case MessageEvent.CHANGE_NOTIFICATION_NUMBER:   // 数量改变
//				if(mNotificationFragment.getShowStatu() !=3) {
//					int number = Integer.parseInt(messageEvent.getMessage());
//					   new QBadgeView(this).bindTarget(notification_number)
//					   .setBadgeNumber(number).setBadgeGravity(Gravity.TOP|Gravity.RIGHT);
//				}
				break;
			case MessageEvent.SHOW_ALL_MONEY:
				String content = messageEvent.getMessage();
                getNewMoney user = new getNewMoney();
                Gson mGson = new Gson();
                user = mGson.fromJson(content, user.getClass());
				SharedPreferences preferences = getSharedPreferences("param", MODE_PRIVATE);
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString("moneyNumber", user.getJxhz());
				editor.putString("moneyTime", user.getKhrq());
				editor.commit();
				boolean isShowMoney = SharedPreferencesUtil.getSharePreferencesByKeyForBoolean(MainTabActivity.this,"paramMoney","isShowMoney");
				mMainFragment.changeAllMoney(user.getJxhz() , user.getKhrq(),isShowMoney);
				break;
		}
	}
	
	@Override
	protected void onDestroy(){
		if(mLocalBroadcastManager != null && mHBroadcastReceiver != null)	
			mLocalBroadcastManager.unregisterReceiver(mHBroadcastReceiver);
		super.onDestroy();
		 EventBus.getDefault().unregister(this);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	// 返回桌面
	    	onExitClick();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public void onExitClick(){
		DialogConfig config = new DialogConfig(this, getResources().getString(R.string.param244), true, exitClickListener);
		config.show();
	}
	
	private OnClickListener exitClickListener = new  OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			TAppTokenModel.resetToken();
			finish();
		}
		
	};
	
	@Override
    protected void setStatusBar() {
        StatusBarUtil.setColor(this, AppUtil.getColor(this, R.color.bank_header), 1);
    }

	@Override
	public boolean onNavigationItemSelected(@NonNull MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId){
			case R.id.home:
				viewPager.setCurrentItem(0);
				return true;

			case R.id.setting:
				viewPager.setCurrentItem(1);
				return true;
		}
		return false;

	}


	private MenuItem menuItem;

    public class MyOnPageChangeListener implements OnPageChangeListener{
        public void onPageScrollStateChanged(int arg0) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        	
        }

        public void onPageSelected(int arg0) {
			menuItem = mBottomNavigation.getMenu().getItem(arg0);
			menuItem.setChecked(true);
        }
    }

	
	/**
	 * ViewPager
	 * @param txt
	 * @param drawable
	 * @param color
	 */
	private void changeStype(TextView txt, Drawable drawable, int color){
		txt.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
		txt.setTextColor(AppUtil.getColor(this, color));
	}
	
	/**
	 * 本地广播
	 * @author arvin
	 *
	 */
	class HBroadcastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO 接收广播
			String action = intent.getAction();
			if (action.equals(BaseAction.action_heart_timeout)){
//				强制退出
//				BaseToast.getInstance().ShowSystemToast(context, "超时");
//				BankApplication.getApp().finishAll();
			}
		}
	}
	
	private IntentFilter getIntentFilter(){
		IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(BaseAction.action_heart_timeout);
        
        return mIntentFilter;
	}

	public void sendBroadcastByLocal(String action){
		Intent intent = new Intent(action);
		sendBroadcastByLocal(intent);
	}
	
    public void sendBroadcastByLocal(Intent intent){
		mLocalBroadcastManager.sendBroadcast(intent);
	}

	@Override
	public void getXtBbGxData(XtBbGxBean mXtBbGxBean) {
		// TODO Auto-generated method stub
		mc = mXtBbGxBean.getMc();
		apkname = mXtBbGxBean.getApkmc();
		verName = mXtBbGxBean.getBbmc();
		verCode = Integer.valueOf(mXtBbGxBean.getBbh());
		
		if (BankApplication.versionCode < verCode) {
			path = mXtBbGxBean.getDz();
			config = new DialogConfig(this, getResources().getString(R.string.param245), true, downloadClickListener);
			config.show();
			config.setCancelable(false);
		}
		/*else {
			this.showMessage("已经是最新版本");
		}*/
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		//BaseToast.getInstance().ShowSystemToast(this, msg);
		try{
			Toast.makeText(MainTabActivity.this, msg, Toast.LENGTH_SHORT).show();
		}catch(IllegalStateException e) {
			
		}catch(Exception e) {
			
		}
	}
	private void download(DownloadBean bean) {
        //这个是非ui线程回调，不可直接操作UI
		String content = GsonUtil.getGson().toJson(bean);
        
		String url = BankApplication.mInstance.url + "bank/fileDownLoadOperate!downLoadByName.do?content="+content;
		
        //这个是ui线程回调，可直接操作UI
        final UIProgressListener uiProgressResponseListener = new UIProgressListenerImpl(mProgressBar.mProgressBar);

        //构造请求
        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(client, uiProgressResponseListener).newCall(request).enqueue(new DownLoadCallback(mHandler));
    }
	
	private Handler mHandler = new Handler(new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub

			mProgressBar.dismiss();
			if (msg.what == 101) {
				
				Bundle bundle = msg.getData();
				String path = bundle.getString("path");
				
		        Intent intent = new Intent(Intent.ACTION_VIEW); 
		        if (Build.VERSION.SDK_INT >= 24) {
		        	 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				        Uri url=FileProvider.getUriForFile(MainTabActivity.this, "com.jph.takephoto.fileprovider", new File(path));
				        intent.setDataAndType(url, "application/vnd.android.package-archive");
		        }else{
		        	intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");  
		        }
//		        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");  
		        startActivity(intent);
			}
			
			
			return false;
		}
	});
	SearchNotificationWindow searchView;
	public class PopNotification implements onNotificationMenuItemClickListener{

		@Override
		public void onRearchAll() {
			mNotificationFragment.setShowStatu(1);
			mNotificationFragment.onGetLocalData(false);
			mPopupMenu.dismiss();
		}

		@Override
		public void onRearchNoRead() {
			mNotificationFragment.setShowStatu(2);
			mNotificationFragment.onGetNoReadData();
			mPopupMenu.dismiss();
		}

		@Override
		public void onRearchRead() {
			mNotificationFragment.setShowStatu(3);
			mNotificationFragment.onGetReadData();
			mPopupMenu.dismiss();
		}

		@Override
		public void onRearchType() {
			mNotificationFragment.setShowStatu(4);
			mPopupMenu.dismiss();
//			srearch_all.setVisibility(View.VISIBLE);
//			go_back.setVisibility(View.VISIBLE);
//			if(null == searchView){
//				searchView = new SearchNotificationWindow(MainTabActivity.this, LayoutParams.MATCH_PARENT,  LayoutParams.WRAP_CONTENT);
//				searchView.setOnSearchClickListener(new searchPopNotifition());  
//			}
//			searchView.showAtLocation(txt_header_title,Gravity.TOP,0,0);
		}

		@Override
		public void onRearchDel() {		// 
			mNotificationFragment.setShowStatu(5);
			mNotificationFragment.OnDelMoreData();
//			header_btn_menu.setText(FInish_DEl);
//			header_btn_menu.setBackground(null);
			mPopupMenu.dismiss();
		}
	}
	
	public class searchPopNotifition implements onSearchListener{

		@Override
		public void onRearch(int type, String key) {
			
		}

		@Override
		public void onRearchNoContent() {
			
		}

		@Override
		public void onRearchHide() {
		
		}
		
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
//		case R.id.header_btn_menu:
//			if(header_btn_menu.getText() == FInish_DEl) {
//				header_btn_menu.setText("");
//				header_btn_menu.setBackgroundResource(R.drawable.bank_menu);
//				mNotificationFragment.OnSureDelMoreData();
//			}else {
//				mPopupMenu.showAsDropDown(header_btn_menu);
//			}
			
//			break;
//		case R.id.sure_search_img:
//		case R.id.sure_search:
//			String content = input_content.getText().toString().trim();
//			if(TextUtils.isEmpty(content)) {
//				Toast.makeText(this, "查询条件不能为空",Toast.LENGTH_SHORT);
//				return ;
//			}
//			mNotificationFragment.OnGetOtherTypeData(selType,content);
//			break;
//		case R.id.go_back:
//		case R.id.go_back_img:
//			input_content.setText("");
//			srearch_all.setVisibility(View.GONE);
			
//			break;
		}
	}


}
